package com.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 18. 四数之和
 * 排序 + 两层循环 + 对撞指针
 *
 * @author fy
 * @date 2022/4/8 8:38
 */
public class Solution18 {

    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length < 4) {
            return res;
        }
        Arrays.sort(nums);
        int n = nums.length;
        for (int i = 0; i < n - 3; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < n - 2; j++) {
                // 这里的条件一定要小心写, 不然无法去重也可能会丢失可能的组合
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int p = j + 1;
                int q = n - 1;
                int t = target - nums[i] - nums[j];
                while (p < q) {
                    if (nums[p] + nums[q] == t) {
                        List<Integer> list = new ArrayList<>();
                        list.add(nums[i]);
                        list.add(nums[j]);
                        list.add(nums[p]);
                        list.add(nums[q]);
                        res.add(list);

                        while (p + 1 < q && nums[p] == nums[p + 1]) {
                            p++;
                        }
                        p++;
                        while (p < q - 1 && nums[q] == nums[q - 1]) {
                            q--;
                        }
                        q--;
                    } else if (nums[p] + nums[q] < t) {
                        p++;
                    } else {
                        q--;
                    }
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{-2, -1, -1, 1, 1, 2, 2};
        int target = 0;
        List<List<Integer>> res = new Solution18().fourSum(nums, target);
        System.out.println(res);
    }

}
